package com.nonintrusive.client.database;

import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

public class ClientDB extends ContentProvider {
	private static final String TAG = "ClientDB";

	private static final String AUTHORITY = "com.nonintrusive.client.database";
	private static final int DATABASE_VERSION = 4;
	private static final String DATABASE_NAME = "clientDB.db";

	private static final int ALL_ROWS = 1;
	private static final int SINGLE_ROW = 2;

	// table Questions
	private static final String TABLE = "questions";

	/**
	 * Specific per client
	 */
	public static final String QUESTION_ID = "_id";
	public static final String MESSAGE = "message";

	public static final String ANSWER1 = "answer1";
	public static final String ANSWER2 = "answer2";
	public static final String ANSWER3 = "answer3";
	public static final String ANSWER4 = "answer4";
	public static final String ANSWER5 = "answer5";

	public static final String NR_ANSWERS = "nr_answers";

	public static final String TAGS = "tags";
	public static final String IS_MY_QUESTION = "is_my_question";
	public static final String IS_ANSWERED = "is_answered";
	public static final String TIMESTAMP = "timestamp";

	public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
			+ "/" + TABLE);
	public static final String CONTENT_TYPE = "questions";
	public static final String CONTENT_ITEM_TYPE = "question";
	public static final String DEFAULT_SORT_ORDER = QUESTION_ID;

	private static HashMap<String, String> sProjectionMap;
	public static final String[] DEFAULT_PROJECTION = new String[] {
			QUESTION_ID, MESSAGE, ANSWER1, ANSWER2, ANSWER3, ANSWER4, ANSWER5,
			TAGS, IS_MY_QUESTION, IS_ANSWERED, TIMESTAMP };

	private static final UriMatcher sUriMatcher;

	static {
		sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		sUriMatcher.addURI(AUTHORITY, TABLE, ALL_ROWS);
		sUriMatcher.addURI(AUTHORITY, TABLE + "/#", SINGLE_ROW);

		sProjectionMap = new HashMap<String, String>();
		sProjectionMap.put(QUESTION_ID, QUESTION_ID);
		sProjectionMap.put(MESSAGE, MESSAGE);
		sProjectionMap.put(ANSWER1, ANSWER1);
		sProjectionMap.put(ANSWER2, ANSWER2);
		sProjectionMap.put(ANSWER3, ANSWER3);
		sProjectionMap.put(ANSWER4, ANSWER4);
		sProjectionMap.put(ANSWER5, ANSWER5);
		sProjectionMap.put(TAGS, TAGS);
		sProjectionMap.put(IS_MY_QUESTION, IS_MY_QUESTION);
		sProjectionMap.put(IS_ANSWERED, IS_ANSWERED);
		sProjectionMap.put(TIMESTAMP, TIMESTAMP);

	}

	private static class DatabaseHelper extends SQLiteOpenHelper {

		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("create table " + TABLE + " (" + QUESTION_ID
					+ " INTEGER PRIMARY KEY, " + MESSAGE + " TEXT, " + ANSWER1
					+ " TEXT, " + ANSWER2 + " TEXT, " + ANSWER3 + " TEXT, "
					+ ANSWER4 + " TEXT, " + ANSWER5 + " TEXT, " + NR_ANSWERS
					+ " TEXT, " + TAGS + " TEXT, " + IS_MY_QUESTION
					+ " BOOLEAN, " + IS_ANSWERED + " BOOLEAN, " + TIMESTAMP
					+ " INTEGER);");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
					+ newVersion + ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS " + TABLE);
			onCreate(db);
		}
	}

	private DatabaseHelper mOpenHelper;

	@Override
	public boolean onCreate() {
		mOpenHelper = new DatabaseHelper(getContext());
		return true;
	}

	@Override
	public String getType(Uri uri) {
		switch (sUriMatcher.match(uri)) {
		case ALL_ROWS:
			return CONTENT_TYPE;

		case SINGLE_ROW:
			return CONTENT_ITEM_TYPE;

		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

		switch (sUriMatcher.match(uri)) {
		case ALL_ROWS:
			qb.setTables(TABLE);
			qb.setProjectionMap(sProjectionMap);
			break;

		case SINGLE_ROW:
			qb.setTables(TABLE);
			qb.setProjectionMap(sProjectionMap);
			qb.appendWhere(QUESTION_ID + "=" + uri.getPathSegments().get(1));
			break;

		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}

		String orderBy;
		if (TextUtils.isEmpty(sortOrder)) {
			orderBy = DEFAULT_SORT_ORDER;
		} else {
			orderBy = sortOrder;
		}

		SQLiteDatabase db = mOpenHelper.getReadableDatabase();
		Cursor c = qb.query(db, projection, selection, selectionArgs, null,
				null, orderBy);

		c.setNotificationUri(getContext().getContentResolver(), uri);
		return c;
	}

	@Override
	public Uri insert(Uri uri, ContentValues initialValues) {
		ContentValues values;

		// Validate the requested uri
		if (sUriMatcher.match(uri) != ALL_ROWS) {
			throw new IllegalArgumentException("Unknown URI " + uri);
		}

		if (initialValues != null) {
			values = new ContentValues(initialValues);
		} else {
			values = new ContentValues();
		}

		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		long rowId = db.insert(TABLE, QUESTION_ID, values);
		if (rowId > 0) {
			final Uri extUri = ContentUris.withAppendedId(CONTENT_URI, rowId);
			getContext().getContentResolver().notifyChange(extUri, null);
			return extUri;
		}

		throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public int update(Uri uri, ContentValues values, String where,
			String[] whereArgs) {

		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int count = 0;
		switch (sUriMatcher.match(uri)) {
		case SINGLE_ROW:
			String id = uri.getPathSegments().get(1);

			count = db.update(TABLE, values,
					QUESTION_ID
							+ "="
							+ id
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);

			break;
		case ALL_ROWS:
			count = db.update(TABLE, values, where, whereArgs);
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}

		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	@Override
	public int delete(Uri uri, String where, String[] whereArgs) {
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int count;

		switch (sUriMatcher.match(uri)) {
		case ALL_ROWS:
			count = db.delete(TABLE, where, whereArgs);
			break;

		case SINGLE_ROW:
			String id = uri.getPathSegments().get(1);

			count = db.delete(TABLE,
					QUESTION_ID
							+ "="
							+ id
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);

			break;

		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}

		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}
}
